import 'dart:math';

import 'package:flutter/material.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:video_player/video_player.dart';

// 视频播放器进度控制视图
class XinDongCommonVideoPlayerProgressControl extends StatefulWidget {
  final VideoPlayerController? videoPlayerController;

  const XinDongCommonVideoPlayerProgressControl({Key? key, required this.videoPlayerController}) : super(key: key);

  @override
  State<XinDongCommonVideoPlayerProgressControl> createState() => _XinDongCommonVideoPlayerProgressControlState();
}

class _XinDongCommonVideoPlayerProgressControlState extends State<XinDongCommonVideoPlayerProgressControl> {
  double currentProgress = 0.0;

  @override
  void initState() {
    super.initState();
    widget.videoPlayerController?.addListener(() async {
      // 播放错误
      if (widget.videoPlayerController!.value.hasError == true) {
        return;
      }
      // 资源时长为0
      if (widget.videoPlayerController!.value.duration.inMilliseconds == 0.0) {
        return;
      }

      try {
        // 正常播放
        Duration position = widget.videoPlayerController!.value.position;
        Duration totalDuration = widget.videoPlayerController!.value.duration;

        if (mounted) {
          setState(() {
            currentProgress = 1.0 * position.inMilliseconds / totalDuration.inMilliseconds;
          });
        }
      } catch (e) {
        mCatchPrint(e);
      }
    });
  }

  @override
  void dispose() {
    widget.videoPlayerController?.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LinearProgressIndicator(
      value: min(1.0, max(0.0, currentProgress)),
      backgroundColor: Colors.black12,
      valueColor: const AlwaysStoppedAnimation<Color>(Colors.grey),
    );
  }
}
